package com.aaa.interceptor;

import com.aaa.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermitsInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的路径  /user/toList.do /user/toEdit.do /user/saveOrUpdate.do ....
        String path = request.getServletPath();

        //判断用户 是否有权限操作该路径 如果有权限就继续访问 否则就跳转到权限不足的界面
        User dbUser = (User) request.getSession().getAttribute("SESSION_USER");
        //获取用户能操作的所有的菜单这块一定要把用户能操作的菜单 登录成功之后放到session中
        //能提高程序的运行效率
        List<String> userNamespaces = (List<String>) request.getSession().getAttribute("PERMITS");
        for (String u : userNamespaces) {
            System.out.println(u);
        }
        //包含
        //截取path的namespace 属性
        String[] namespaces = path.split("/");
        String namespace = null;
        if (namespaces.length == 3) {
            namespace = namespaces[1];
        }
        if (namespace != null && userNamespaces.contains(namespace)) {
            return true;
        } else {
            //重定向到权限不足的界面
            response.sendRedirect(request.getContextPath() + "/noPermit");
            return false;
        }
     }
    }
